<?php

/**
 * @Author: king
 * @Date:   2019-05-04 16:52:02
 * @Last Modified by:   king
 * @Last Modified time: 2019-05-26 10:51:21
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use AstroTool\Cache\CacheManage;
use App\Models\Api\Base;
use Cache;

class LanmeiCounselorAnswerOnlooker extends Base
{
    protected $table = 'counselor_answer_onlooker';

    /**
     * 通过数据库获取用户围观的答案ID
     * @param $uid
     * @return array
     * @throws ApiException
     */
    public function getUserReadAnswerIdsByData($uid)
    {
        try
        {
            $result = $this->where('uid', $uid)->pluck('ca_id')->toArray(); // 获取用户围观的所有答案ID
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $result;
    }

    /**
     * 新增围观答案
     * @param $data
     * @return int
     * @throws ApiException
     */
    public function createAnswerRead($data)
    {
        $uid = $data['uid'];
        try
        {
            $this->save($data);
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        CacheManage::getInstance()->setCacheConfig('users_answer_read', $uid)
            ->sAddIocData([$data['ca_id']],'list', function () use ($uid)
            {
                return $this->getUserReadAnswerIdsByData($uid);
            });

        return true;
    }

    /**
     * 用户是否围观了当前答案
     * @param $uid
     * @param $caId
     * @return bool
     * @throws ApiException
     */
    public function userIsReadAnswer($uid, $caId)
    {
        $result = CacheManage::getInstance()->setCacheConfig('users_answer_read', $uid)
            ->sDataIsMember($caId, 'list', function () use ($uid)
            {
                return $this->getUserReadAnswerIdsByData($uid);
            });

        return $result;
    }

    /**
     * 获取用户围观的所有答案ID
     * @param $uid
     * @return array
     * @throws ApiException
     */
    public function getUserReadAnswerIds($uid)
    {
        $result = CacheManage::getInstance()->setCacheConfig('users_answer_read', $uid)
            ->sGetIocData('list', function () use ($uid)
            {
                return $this->getUserReadAnswerIdsByData($uid);
            });

        return $result;
    }
}
